var express =require('express');
var router =express.Router();
var PostModel = require('../models/posts');
var Dupjson=require('circular-json');

router.get('/',function(req,res,next){
  var author =  req.query.author;
  console.log('我到这里啦哈哈哈哈.......')
  PostModel.getPosts(author)
  .then(function (posts) {
   
    res.render('posts', {
      posts: posts
    });
  })
  .catch(next);  
});

router.post('/',function(req,res,next){
    var author = req.session.user._id;
    var title = req.fields.title;
    var content = req.fields.content;
    var d =new Date();
    var publicData = d.toLocaleString(); 
    // 校验参数
    try {
      if (!title.length) {
        throw new Error('请填写标题');
      }
      if (!content.length) {
        throw new Error('请填写内容');
      }
    } catch (e) {
      return res.redirect('back');
    }
  
    var post = {
      author: author,
      title: title,
      content: content,
      time: publicData
    };
  
    PostModel.create(post)
      .then(function (result) {
        // 此 post 是插入 mongodb 后的值，包含 _id
        post = result.ops[0];
       
        // 发表成功后跳转到该文章页
        res.redirect(`/posts/${post._id}`);
      })
      .catch(next);
});

// GET /posts/create 发表文章页
router.get('/create', function(req, res, next) {
    res.render('create');
});
  
// GET /posts/:postId 单独一篇的文章页
router.get('/:postId', function(req, res, next) {
  var postId = req.params.postId;
  Promise.all([
    PostModel.getPostById(postId)// 获取文章信息
  ])
  .then(function (result) {
    var post = result[0];
    if (!post) {
      throw new Error('该文章不存在');
    }
    
    res.render('post', {
      post: post
    });
  })
  .catch(next);

});
  
// GET /posts/:postId/edit 更新文章页
router.get('/:postId/edit', function(req, res, next) {
  var postId = req.params.postId; 
  var author = req.session.user._id;

  PostModel.getPostById(postId)
    .then(function (post) {
      if (!post) {
        throw new Error('该文章不存在');
      }
      if (author.toString() !== post.author._id.toString()) {
        throw new Error('权限不足');
      }
      res.render('editPost', {
        post: post
      });
    })
    .catch(next);   
});
  
// POST /posts/:postId/edit 更新一篇文章
router.post('/:postId/edit', function(req, res, next) {
  var postId = req.params.postId; 
  var author = req.session.user._id; 
  var title = req.fields.title; 
  var content = req.fields.content;

  PostModel.updatePostById(postId, author, { title: title, content: content })
    .then(function () {
      // 编辑成功后跳转到改文章页
      res.redirect(`/posts/${postId}`);
    })
    .catch(next);
});
  
// GET /posts/:postId/remove 删除一篇文章
router.get('/:postId/remove', function(req, res, next) {
  var postId = req.params.postId; 
  var author = req.session.user._id;

  PostModel.delPostById(postId, author)
    .then(function () {
      // 删除成功后跳转到主页
      res.redirect('/posts');
    })
    .catch(next);
});
  

module.exports = router;